# Create your views here.

import os

from django.template import Context, loader
from django.http import HttpResponse
from django import forms
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response

from settings import DIRS

import LoadLogToActivity

title = "IASNA Tools: IASNA-Teamquest Convert XML"
welcome = "Welcome to IASNA System. This module IASNA-TeamQuest enable you to convert your TeamQuest data in xml format to IASNA xml format."
menu = {"Actions": {"status": "active", "short_name": "Actions", "url": "/teamquest/"}, 
        "Results": {"status": "inactive", "short_name": "Results", "url": "/teamquest/results"}}

functions1 = {"Convert to IASNA XML": {"status": "active", "short_name": "... to IASNA", "url": "/teamquest/"}}
functions2 = {}
modules = {"Iasna Core": {"status": "inactive", "short_name": "iasna", "url": "/iasna/"}, 
           "Iasna Teamquest": {"status": "active", "short_name": "teamquest", "url": DIRS["TEAMQUEST_URL"]},
           "Iasna Reflexion": {"status": "inactive", "short_name": "reflexion", "url": DIRS["REFLEXION_URL"]},
           "Iasna Recommendation": {"status": "inactive", "short_name": "recommendation", "url": DIRS["RECOMMENDATION_URL"]},
           }

TEMPLATES_MEDIA_URL = DIRS["PROJECT_MEDIA_URL"] + 'myTemplates/snow-flakes/'

#configurar active en grafico
def link_activated(list_links, key):
    for list_link in list_links:
        if list_link.lower().replace(" ", "_") == key.lower().replace(" ", "_"):
            list_links[list_link]["status"] = "active"
        else: list_links[list_link]["status"] = "inactive"

def index(request):
    link_activated(menu, "Actions")
    link_activated(functions1, "Convert to IASNA XML")
    
    t = loader.get_template('teamquest1.html')
    subtitle = 'Actions over Xml TeamQuest files'
    fileupload = UploadFileForm()
    
    c = Context({
        'title': title,
        'subtitle': subtitle,
        'welcome': welcome + "\n\nRemember, once to upload this file successful end it will convert to IASNA format for its SNA Analysis",
        'menu': menu,
        'functions': functions1,
        #'options': functions1,
        'fileupload': fileupload,
        'modules': modules,
        'TEMPLATES_MEDIA_URL': TEMPLATES_MEDIA_URL,
    })
    return HttpResponse(t.render(c))

def list_files_in_path(path, ext):
    files = os.listdir(path)
    for file in files:
        if not file.lower().endswith('.' + ext.lower()):
            files.remove(file)
    return files

def results(request):
    functions2 = {}
    fun2 = list_files_in_path(DIRS["CORE_MEDIA_ROOT"], 'xml')
    for f in fun2:
        functions2[f.replace(".xml", "")] = {"status": "inactive", "url": "/teamquest/results/" + f.replace(".xml", "")}
    
    link_activated(menu, "Results")
    link_activated(functions2, "")
    
    t = loader.get_template('teamquest1.html')
    subtitle = 'Uploaded files with Xml TeamQuest format'
    welcome = '\n\r\n\rIt is displaying all Xml uploaded TeamQuest files, select to any link show below'
    
    c = Context({
        'title': title,
        'subtitle': subtitle,
        'welcome': welcome,
        'menu': menu,
        'functions': functions2,
        'options': functions2,
        'modules': modules,
        'TEMPLATES_MEDIA_URL': TEMPLATES_MEDIA_URL,
    })
    return HttpResponse(t.render(c))

def view_xmlfile(request, xmlfile):
    functions2 = {}
    fun2 = list_files_in_path(DIRS["CORE_MEDIA_ROOT"], 'xml')
    for f in fun2:
        functions2[f.replace(".xml", "")] = {"status": "inactive", "url": "/teamquest/results/" + f.replace(".xml", "")}
    
    link_activated(menu, "Results")
    link_activated(functions2, xmlfile)
    
    t = loader.get_template('teamquest1.html')
    subtitle = 'Displaying a Xml file: ' + xmlfile
    #welcome += '\n\r\n\rIt is displaying all Xml uploaded TeamQuest files, select to any link show below'
    
    #myxmlfile = LoadLogToActivity.loadLogToActivity(xmlfile)
    myxmlfile_link = DIRS["CORE_MEDIA_ROOT"] + xmlfile + '.xml'
    link_to_module = {'text': 'If you want view analysis for this log use the below link to access to IASNA-core module and so analysis the interaction log.',
                      'name': 'IASNA - Core: analysis to ' + xmlfile,
                      'url': DIRS["CORE_URL"] + 'analysis/' + xmlfile, }
    
    c = Context({
        'title': title,
        'subtitle': subtitle,
        'welcome': welcome,
        'menu': menu,
        'functions': functions2,
        'xmlfile': xmlfile,
        'link_to_module': link_to_module,
        #'xmlfile_link': myxmlfile_link,
        'modules': modules,
        'TEMPLATES_MEDIA_URL': TEMPLATES_MEDIA_URL,
    })
    return HttpResponse(t.render(c))
    


# uploading xml files

class UploadFileForm(forms.Form):
    title = forms.CharField(max_length=50)
    file  = forms.FileField()

def upload_file(request):
    if request.method == 'POST':
        form = UploadFileForm(request.POST, request.FILES)
        if form.is_valid():
            myfile = request.FILES['file']
            handle_uploaded_file(myfile)
            data = LoadLogToActivity.loadLogToActivity(myfile.name.replace(".xml", ""))
            LoadLogToActivity.saveLogToActivity(myfile.name.replace(".xml", ""), data)
            return results(request)
    else:
        form = UploadFileForm()
    return render_to_response('teamquest1.html', {
        'fileupload': form, 
        "welcome": welcome, 
        'subtitle': 'Error uploading the file', 
        'modules': modules,
        'TEMPLATES_MEDIA_URL': TEMPLATES_MEDIA_URL, })
    

def handle_uploaded_file(f):
    try:
        destination = open(DIRS["TEAMQUEST_MEDIA_ROOT"] + f.name, 'wb+')
        for chunk in f.chunks():
            destination.write(chunk)
        destination.close()
    except IOError: print 'Error writing the file ' + f.name

